package com.nanhang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanhang.common.util.PageResult;
import com.nanhang.entity.department;
import com.nanhang.entity.employee;
import com.nanhang.mapper.employeeMapper;
import com.nanhang.service.DepartmentService;
import com.nanhang.service.employeeService;
import com.nanhang.vo.SnowflakeIdWorker;
import com.nanhang.vo.employeeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class employeeServiceImpl extends ServiceImpl<employeeMapper, employee> implements employeeService {
@Autowired
private DepartmentService departmentService;
    // 创建 Snowflake ID 生成器
    private final SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1); // workerId 和 datacenterId 可以根据需要设置

    // 1. 分页查询
    @Override
    public PageResult<employee> findByPage(Integer page, Integer pageSize) {
        Page<employee> page1 = this.page(new Page<>(page,pageSize));
        return new PageResult<>(page1.getRecords(),page1.getPages());
    }
//2,条件分页查询
@Override
public PageResult<employee> search(Integer page, Integer pageSize, employeeVO vo) {

    // 封装查询条件
    QueryWrapper<employee> wrapper = new QueryWrapper<>();
    wrapper.like(StrUtil.isNotBlank(vo.getEname()), "ename",  vo.getEname() )
            .like(StrUtil.isNotBlank(vo.getSex()), "sex", vo.getSex())
            .eq(vo.getDid() != null && vo.getDid() != 0, "did", vo.getDid());
    // 分页查询
    Page<employee> page1 = this.page(new Page<>(page, pageSize), wrapper);
    // 获取部门名称
    page1.getRecords().forEach(em -> {
        department  department = departmentService.getById(em.getDid());
        em.setDname(department.getDname());
    });
    // 封装分页结果
    return new PageResult<>(page1.getRecords(),page1.getTotal());
}
//添加
@Override
public boolean add(employee employee) {
    // 使用 Snowflake 算法生成全局唯一的工号
    Long newEmployeeCode = idWorker.nextId();

    // 设置员工的工号
    employee.setEid(Math.toIntExact(newEmployeeCode));

        return this.save(employee);
}

}
